﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Threading;
using System.IO;

namespace HSE.Common
{
    public class HttpClientPost
    {
        private byte[] postData;
        private string postStrData;
         SynchronizationContext currentContext;
 
        SendOrPostCallback sopc;
 
        public void PostData(string url, byte[] data, SynchronizationContext _currentContext, SendOrPostCallback _sopc)
         {
             currentContext = _currentContext;
             Uri endpoint = new Uri(url);
             sopc = _sopc;
             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endpoint);
             request.Method = "POST";
             request.ContentLength = data.Length;
             request.ContentType = "text/xml";
             postData = data;
            
             request.BeginGetRequestStream(new AsyncCallback(RequestReadySocket), request);
         }

        public void PostData(string url, string data, SynchronizationContext _currentContext, SendOrPostCallback _sopc)
         {
             currentContext = _currentContext;
             Uri endpoint = new Uri(url);
             sopc = _sopc;
             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endpoint);
             request.Method = "POST";
             //request.ContentLength = data.Length;
             request.ContentType = "application/x-www-form-urlencoded";
             postStrData = data;
             request.BeginGetRequestStream(new AsyncCallback(RequestReadySocket), request);
         }
 
        private void RequestReadySocket(IAsyncResult asyncResult)
         {
             WebRequest request = asyncResult.AsyncState as WebRequest;
             Stream requestStream = request.EndGetRequestStream(asyncResult);
 
            using (StreamWriter writer = new StreamWriter(requestStream))
             {
                 writer.Write(postData);
                 writer.Flush();
             }
 
            request.BeginGetResponse(new AsyncCallback(ResponseReadySocket), request);
         }
 
        private void ResponseReadySocket(IAsyncResult asyncResult)
         {
             WebRequest request = asyncResult.AsyncState as WebRequest;
             WebResponse response = request.EndGetResponse(asyncResult);
             using (Stream responseStream = response.GetResponseStream())
             {
                 StreamReader reader = new StreamReader(responseStream);
                 string paramStr = reader.ReadToEnd();
                 currentContext.Post(sopc, paramStr);
             }
         }
     }
    
}
